package cn.knet.sp.ncrm.modules.sys.security.cas;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


/**
 * 主要用作拦截问系统的logout 请求
 *
 * @INFO:
 * @Author: Feng Yapeng
 * @Time: 2015/5/14 15:29
 */
public class SystemCasLogoutFilter extends AdviceFilter {

	private static String casLogoutURL;

	private static String service;

	private static HashMap<String, String> logoutParams;


	public String getCasLogoutURL() {
		return casLogoutURL;
	}

	public void setCasLogoutURL(String casLogoutURL) {
		this.casLogoutURL = casLogoutURL;
	}

	public static HashMap<String, String> getLogoutParams() {
		if (logoutParams == null) {
			logoutParams = new HashMap<String, String>();
			logoutParams.put("service", service);
		}
		return logoutParams;
	}

	public String getService() {
		return service;
	}

	public void setService(String service) {
		this.service = service;
	}

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		//====预处理/前置处理
		return true;//返回false将中断后续拦截器链的执行
	}

	@Override
	protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
		//====后处理/后置返回处理

	}

	@Override
	public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception)
			throws Exception {
		//====完成处理/后置最终处理
	}


	@Override
	public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null) {
			WebUtils.issueRedirect(request, response, service);
		} else {
			// 由于jmsLogoutMessageService 会处理session 问题，故这里不处理
			WebUtils.issueRedirect(request, response, casLogoutURL, getLogoutParams());
		}
	}
}
